<template>
  <div>
    <div>
      <el-input
          type="text"
          placeholder="商品名称"
          v-model="name"
          style="width: 180px;float: left;padding-left: 10px"
          clearable></el-input>&nbsp;&nbsp;
      <el-select v-model="goodsTypeId" clearable placeholder="请选择商品类型" style="float: left;padding-left: 10px">
        <el-option
            v-for="item in goodsTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            style="float: left">
        </el-option>
      </el-select>&nbsp;&nbsp;&nbsp;&nbsp;
      <el-button type="primary" icon="el-icon-search"  @click="select" style="margin-left: -100px">搜索</el-button>&nbsp;&nbsp;
      <el-button type="primary"  @click="save" style="margin-left: 10px">新增</el-button>&nbsp;&nbsp;
      <el-button type="primary" @click="deleteMany"  style="margin-left: 10px">批量删除</el-button>&nbsp;&nbsp;
    </div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
    >
      <el-table-column
          prop="name"
          label="商品"
          width="120">
      </el-table-column>
      <el-table-column
          prop="costPrice"
          label="成本价格"
          width="120">
      </el-table-column>
      <el-table-column
          prop="salePrice"
          label="销售单价"
          width="120">
      </el-table-column>
      <el-table-column
          prop="goodsType.name"
          label="商品类型"
          width="120">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.row)" >编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!--  弹窗-->
    <el-dialog title="商品信息编辑" :visible.sync="dialogFormVisible"  @close="clearForm">
      <el-form :model="form" :rules="rules" ref="formref" >
        <el-form-item label="商品名称：" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价格："  :label-width="formLabelWidth" prop="costPrice">
          <el-input v-model="form.costPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价格：" :label-width="formLabelWidth"  prop="salePrice" >
          <el-input v-model="form.salePrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品类型："  prop="goodsTypeId" :label-width="formLabelWidth" >
          <el-select v-model="form.goodsTypeId" clearable placeholder="请选择类型">
            <el-option
                v-for="item in goodsTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                style="width: 200px">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="diaSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "shopGoods",
  data(){
    let priceData =async (rule, value, callback) => {
      if(isNaN(value)) {
        return callback(new Error('价格必须是数字'));
      }
      if(value<0){
        return callback(new Error('价格必须大于0'));
      }
      callback()
    };
    return {
      name:'',
      goodsTypeId:'',
      tableData:[],
      curPage:1,
      pageSize:5,
      total:0,
      goodsTypes:[],
      form:{
        id:'',
        name:'',
        costPrice:'',
        salePrice:'',
        goodsTypeId:'',
        shopId: 0,
      },
      dialogFormVisible:false,
      formLabelWidth:'100px',
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        costPrice: [
          { required: true, message: '请输入成本价格', trigger: 'blur' },
          { validator: priceData, trigger: 'blur' }
        ],
        salePrice: [
          { required: true, message: '请输入销售价格', trigger: 'blur' },
          { validator: priceData, trigger: 'blur' }
        ],
        goodsTypeId: [
          { required: true, message: '请选择所属院系', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    //加载表格数据
    async query(){
      let item = sessionStorage.getItem('shopId');
      this.form.shopId= item.substring(0,item.indexOf(','))
      let resp = await this.$axios.get('/goods/selectByShopId',{
        params:{
          curPage:this.curPage,
          pageSize:this.pageSize,
          name:this.name,
          goodsTypeId:this.goodsTypeId,
          shopId:this.form.shopId
        }
      })
      this.tableData = resp.data.data
      this.total=resp.data.total
    },
    //更换每页最大记录数
    handleSizeChange(val) {
      this.viewNum=val
      this.query()
    },
    //切换当前页
    handleCurrentChange(val) {
      this.curPage=val
      this.query()
    },
    //修改
    handleEdit(row) {
      this.dialogFormVisible=true
      this.form.id=row.id
      this.form.shopId=this.shopId
      this.form.name=row.name
      this.form.costPrice=row.costPrice
      this.form.salePrice=row.salePrice
      this.form.goodsTypeId=row.goodsType.id
    },
    //删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        let resp=await this.$axios.get('/goods/dropBatch?id='+row.id+'&shopId='+this.form.shopId)
        if(resp.data.code===200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.query()
        }else{
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //新增
    save(){
      this.dialogFormVisible=true
    },
    diaSave(){
      this.$refs.formref.validate( async (valid) => {

        if (valid) {
          let url
          if(this.form.id===''){
            url='/goods/save'
          }else {
            url='/goods/modify'
          }
          let resp = await this.$axios.get(url,{
            params:this.form
          })
          if(resp.data.code===200){
            this.query()
            this.dialogFormVisible=false
          }else{
            alert('编辑失败')
            this.dialogFormVisible=false
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //多条件查询
    select(){
      this.curPage=1
      this.query()
    },
    //批量删除
    async deleteMany(){
      let selected = this.$refs.multipleTable.selection;
      if(selected.length===0){
        this.$message({
          message: '你还没有选择要删除的商品',
          type: 'warning'
        });
        return
      }
      let ids='?'
      for (let i = 0; i < selected.length; i++) {
        ids+='ids='+selected[i].id+'&'
      }
      ids=ids.substring(0,ids.length-1)
      ids+=this.shopId
      let resp=await this.$axios.get('/goods/dropBatch'+ids)
      if(resp.data.code===200){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.query()
      }else{
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
      }
    },
    //关闭弹窗
    clearForm(){
      this.form.id=''
      this.form.name=''
      this.form.costPrice=''
      this.form.salePrice=''
      this.form.goodsTypeId=''
      this.$refs.formref.resetFields()
    },
  },
  created: async function () {
    this.query()
    let res=await this.$axios.get('/goodsType/queryAll')
    this.goodsTypes=res.data.data
  }

}
</script>

<style scoped>

</style>